package bjut.zrpc.core.optimization.netty;

import bjut.zrpc.core.optimization.bean.ZRpcServiceBean;
import bjut.zrpc.core.optimization.constant.ZRpcConstant;
import bjut.zrpc.core.optimization.utils.ShutdownHookUtil;
import bjut.zrpc.core.optimization.utils.ThreadPoolUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @Author: zhuzhiming
 * @Date: 2022/6/23 23:39
 */
@Component
@Slf4j
public class NettyServer {

    private EventLoopGroup bossGroup;
    private EventLoopGroup workerGroup;
    private ServerBootstrap serverBootstrap;
    private DefaultEventLoopGroup defaultEventLoopGroup;

    public void start() {

        try {

            ShutdownHookUtil.shutdown();

            bossGroup = new NioEventLoopGroup(1);
            workerGroup = new NioEventLoopGroup();
            defaultEventLoopGroup = new DefaultEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2, ThreadPoolUtil.buildThreadFactory("netty-server", true));
            serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childOption(ChannelOption.SO_BACKLOG, 128)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new NettyServerInitializer(defaultEventLoopGroup));

            ChannelFuture channelFuture = serverBootstrap.bind(ZRpcConstant.SERVICE_HOST, ZRpcConstant.NETTY_SERVER_PORT).sync();

            channelFuture.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            log.error(e.getMessage());
        } finally {

            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            defaultEventLoopGroup.shutdownGracefully();

        }

    }


}
